package com.allwees.bs.c.common.aop;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.allwees.core.common.util.http.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Aspect
@Component
public class MethodConsumeTimeAop {

    private static final Gson GSON = new GsonBuilder()
            .setLenient()
            .create();

    @Pointcut("execution(* com.allwees.bs.c..*.controller..*(..))")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        String method = signature.getDeclaringType().getSimpleName() + "." + signature.getName();
        Object[] args = pjp.getArgs();
        StringBuilder builder = new StringBuilder("===> ").append(method);
        if(args != null && args.length > 0){
            List<Object> pargs = new ArrayList<>(args.length);
            for (Object arg : args) {
                if (arg instanceof ServletRequest || arg instanceof ServletResponse){
                    continue;
                }
                pargs.add(arg);
            }
            builder.append(",params:").append(GSON.toJson(pargs));
            builder.append(",context:").append(RequestContext.getContext());
        }
        log.info(builder.toString());

        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        long timeMillis = end - start;
        log.info("===> {},time spent:{}", method, timeMillis);
        return result;
    }
}